package com.bt.lms.ui.action.enp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bt.lms.constants.EnpBizTypeConstant;
import com.bt.lms.entity.EnrollmentPlan;
import com.bt.lms.entity.page.Page;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.enp.EnrollmentPlanList;
import com.bt.lms.ui.vo.enp.EnrollmentPlanListVo;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.layout.HBox;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 招生计划首页事件
 *
 * @author 李鹏
 */
public class EnpPageAction implements EventHandler {

    /**
     * 招生计划主页面
     */
    private EnrollmentPlanList enrollmentPlanList;

    /**
     * 表格
     */
    public TableView tableView;

    public EnpPageAction(EnrollmentPlanList enrollmentPlanList, TableView tableView) {
        this.enrollmentPlanList = enrollmentPlanList;
        this.tableView = tableView;
    }


    @Override
    public void handle(Event event) {

        //分页条件模型
        Page page = new Page();
        byte[] bytes = handleReqMsg(page);

        //组网
        Socket socket = getNet();

        //发送消息
        boolean flag = sendReq(socket, bytes);

    }

    /**
     * 发送信息
     * 1.将消息转为字节流
     * 2.发送
     *
     * @param socket 发送的socket
     * @param bytes  要发送的消息
     * @return
     */
    private boolean sendReq(Socket socket, byte[] bytes) {
        try {
            //发送请求消息
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush(); //冲刷

            //接收回应信息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf);
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();
            Page page = JSONObject.parseObject(data, Page.class);
            List records = page.getRecords(); //查询数据列表

            List<EnrollmentPlan> enrollmentPlans = new ArrayList<>();//给个集合
            //循环取数据
            for (int i = 0; i < records.size(); i++) {
                Object enpObj = records.get(i);
                String enpStr = enpObj.toString();
                EnrollmentPlan enrollmentPlan = JSONObject.parseObject(enpStr, EnrollmentPlan.class);
                enrollmentPlans.add(enrollmentPlan); //放入集合
            }

            ArrayList<EnrollmentPlanListVo> enrollmentPlanListVos = new ArrayList<>();

            for (int i = 0; i < enrollmentPlans.size(); i++) {
                EnrollmentPlan enrollmentPlan = enrollmentPlans.get(i);
                //招生计划编号
                String code = enrollmentPlan.getCode();
                //招生计划名称
                HBox nameHBox = new HBox();
                Label nameLab = new Label("");
                nameHBox.getChildren().add(nameLab);

                //招生层次
                Integer level = enrollmentPlan.getLevel();
                String levelStr = null;
                switch (level) {
                    case 1:
                        levelStr = "不限";
                        break;
                    case 2:
                        levelStr = "高中";
                        break;
                    case 3:
                        levelStr = "大专";
                        break;
                    case 4:
                        levelStr = "本科";
                        break;
                    case 5:
                        levelStr = "本科以上";
                        break;
                    case 6:
                        levelStr = "其他";
                        break;
                }
                //招生专业
                Integer major = enrollmentPlan.getMajor();
                String majorStr = null;
                switch (major) {
                    case 1:
                        majorStr = "不限";
                }

                //关联教学计划
                Long teachPlanId = enrollmentPlan.getTeachPlanId();
                String teachPlanIdStr = teachPlanId.toString();
                //学习中心
                Long studyCenId = enrollmentPlan.getStudyCenId();
                String studyCenIdStr = studyCenId.toString();
                //开始时间
                LocalDate startTime = enrollmentPlan.getStartTime();
                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String startTimeStr = startTime.format(fmt);
                //截止时间
                LocalDate stopTime = enrollmentPlan.getStopTime();
                DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String stopTimeStr = stopTime.format(fmt1);

                //计划招生人数
                Integer population = enrollmentPlan.getPopulation();
                String populationStr = Integer.toString(population);

                //报名人数
                Integer regPopulation = enrollmentPlan.getRegPopulation();
                String regPopulationStr = Integer.toString(regPopulation);
                //审核通过人数
                Integer reviewPopulation = enrollmentPlan.getReviewPopulation();
                String reviewPopulationStr = Integer.toString(reviewPopulation);
                //录取人数
                Integer admitPopulation = enrollmentPlan.getAdmitPopulation();
                String admitPopulationStr = Integer.toString(admitPopulation);

                //状态
                Integer status = enrollmentPlan.getStatus();
                String statusStr = null;
                switch (status) {
                    case 1:
                        statusStr = "未开始";
                        break;
                    case 2:
                        statusStr = "已完成";
                        break;
                    case 3:
                        statusStr = "报名中";
                        break;
                    case 4:
                        statusStr = "审核中";
                        break;
                }
                //启用状态
                Integer startStatus = enrollmentPlan.getStartStatus();
                String startStatusStr = null;
                switch (startStatus) {
                    case 1:
                        startStatusStr = "暂停";
                        break;
                    case 2:
                        startStatusStr = "启用";
                        break;
                }
                //操作盒子
                HBox operationHBox = new HBox();
                //未开始/暂停
                if (status.equals(1) && startStatus.equals(1)) {
                    Button editBtn = new Button("编辑");
                    editBtn.setCursor(Cursor.HAND);
                    Button startBtn = new Button("启用");
                    startBtn.setCursor(Cursor.HAND);
                    Button deleteBtn = new Button("删除");
                    deleteBtn.setCursor(Cursor.HAND);
                    operationHBox.getChildren().addAll(editBtn, startBtn, deleteBtn);
                }
                //已完成/启用
                if (status.equals(2) && startStatus.equals(2)) {

                }
                //报名中/启用
                if (status.equals(3) && startStatus.equals(2)) {
                    Button stopBtn = new Button("暂停");
                    stopBtn.setCursor(Cursor.HAND);
                    operationHBox.getChildren().add(stopBtn);
                }
                //审核中/启用
                if (status.equals(4) && startStatus.equals(2)) {
                    Button overBtn = new Button("完成");
                    overBtn.setCursor(Cursor.HAND);
                    operationHBox.getChildren().add(overBtn);
                }
                //未开始/启用
                if (status.equals(1) && startStatus.equals(2)) {
                    Button editBtn = new Button("编辑");
                    editBtn.setCursor(Cursor.HAND);
                    Button startBtn = new Button("启用");
                    startBtn.setCursor(Cursor.HAND);
                    Button deleteBtn = new Button("删除");
                    deleteBtn.setCursor(Cursor.HAND);
                    Button overBtn = new Button("完成");
                    overBtn.setCursor(Cursor.HAND);
                    operationHBox.getChildren().addAll(editBtn, startBtn, deleteBtn, overBtn);
                }


                EnrollmentPlanListVo enrollmentPlanListVo = new EnrollmentPlanListVo(code, nameHBox, levelStr, majorStr, teachPlanIdStr, studyCenIdStr,
                        startTimeStr, stopTimeStr, populationStr, regPopulationStr, reviewPopulationStr, admitPopulationStr, statusStr, startStatusStr, operationHBox);
                enrollmentPlanListVos.add(enrollmentPlanListVo);
            }

            ObservableList<EnrollmentPlanListVo> enrollmentPlanListVos1 = FXCollections.observableArrayList(enrollmentPlanListVos);
            tableView.setItems(enrollmentPlanListVos1); //数据放入表格中

        } catch (IOException e) {
//            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 获取网络
     *
     * @return socket
     */
    private Socket getNet() {

        String serverIp = "127.0.0.1";
        int serverPort = 8888;
        Socket socket = null;

        try {
            socket = new Socket(serverIp, serverPort);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return null;
        }

        return socket;

    }


    /**
     * 将用户输入的信息处理成我们规定的请求信息
     * 组包
     *
     * @param page 用户输入
     * @return 请求消息
     */
    private byte[] handleReqMsg(Page page) {
        //消息
        ReqMsg reqMsg = new ReqMsg();

        //业务类型
        reqMsg.setBizType(EnpBizTypeConstant.ENP_PLAN_PAGE_CONDITION_QUERY);

        String enpStr = JSON.toJSONString(page);
        //数据带走
        reqMsg.setData(enpStr);

        byte[] bytes = reqMsg.toBytes();

        return bytes;
    }
}
